import urllib.request as request
import urllib.parse as parse
import json

zh_str = input("请输入需要翻译的文字: ")
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc'
datas = {}
datas['i'] = zh_str
datas['type'] = 'AUTO'
datas['doctype'] = 'json'
datas['keyfrom'] = 'fanyi.web'
datas['xmlVversion'] = '2.1'
datas['action'] = 'FY_BY_CLICKBUTTION'
datas['ue'] = 'UTF-8'
datas['typoResult'] = 'true'

datas = parse.urlencode(datas).encode('utf-8')
response = request.urlopen(url,datas,timeout=50)
responseData = response.read().decode('utf-8')
# print(responseData)
 
# 将 JSON 对象转换为 Python 字典
data2 = json.loads(responseData)
# print ("Python 原始数据：", repr(datas))
# print ("JSON 对象：", data2)
# for i in data2 : 
#     print("data2[",i,"]: ",data2[i])
translateResult = data2['translateResult']
# print(type(translateResult))
en_str = ""
for dict_str in translateResult[0] :
    en_str += dict_str.get("tgt")
print("翻译后:",en_str)

